package com.wu.service.impl;

import com.wu.pojo.model.UserToken;
import com.wu.service.UserFriendsService;
import com.wu.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import static com.wu.constant.Constant.*;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-19 20:26
 */
@Service

public class UserFriendsServiceImpl implements UserFriendsService {

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<String> getFriendIdByUserId() {
        UserToken userToken = tokenUtils.parseTokenToUserToken();
        String userId = userToken.getUserId();
        Set<Object> ids = redisTemplate.opsForSet().members(userId + _FOCUS);
        ArrayList<String> arrayList = new ArrayList<>();
        Iterator<Object> iterator = ids.iterator();
        while (iterator.hasNext()) {
            arrayList.add((String) iterator.next());
        }
        return arrayList;
    }

    @Override
    public void deleteById(String userFriendsId) {
        UserToken userToken = tokenUtils.parseTokenToUserToken();
        String userId = userToken.getUserId();
        redisTemplate.opsForSet().remove(userId + _FOCUS, userFriendsId);
        redisTemplate.opsForSet().remove(userFriendsId + _FANS, userId);
    }

    @Override
    public void addFriend(String friendId) {
        UserToken userToken = tokenUtils.parseTokenToUserToken();
        String userId = userToken.getUserId();
        redisTemplate.opsForSet().add(userId + _FOCUS, friendId);
        redisTemplate.opsForSet().add(friendId + _FANS, userId);
    }
}
